//
//  VideoFeedViewController.swift
//  ios_swift_demo1
//
//  Created by liutao on 2020/7/17.
//  Copyright © 2020 lt. All rights reserved.
//
import UIKit
import RxSwift
import RxCocoa
import MediaPlayer
import MJRefresh
import UIKit
import Alamofire
import MediaPlayer
import AVKit
import MBProgressHUD
import Photos


enum RightButtonTouchType {
    case like
    case collection
    case download
    case copyText
    case shareSave
    case shareFriend
    case shareFriendCircle
}

class VideoFeedViewController: UIViewController, MBProgressHUDDelegate{
    
    private var currentSubject: BehaviorRelay<Int> = BehaviorRelay(value: 0)
    private var bag: DisposeBag = DisposeBag()
    private var currentObserver: Disposable?
    
    private var tableView: UITableView
    
    private var popMenuButton:UILabel!
    
    private var popMenuButtonIcon:UIImageView!
    
    private var popMenu:SwiftPopMenu!
    
    private let viewModel: VideoListViewModel = VideoListViewModel()
    
    private var progressHUD : MBProgressHUD!
    
    private var cancelledData : Data?//用于停止下载时,保存已下载的部分
    private var downloadRequest:DownloadRequest!//下载请求对象
    private var destination:DownloadRequest.DownloadFileDestination!//下载文件的保存路径
    private var rightButtonTouchType:RightButtonTouchType = .download
    
    var currentTrillEntity: TrillEntity!
        
    required init() {
        tableView = UITableView(frame: CGRect.zero, style: .plain)
        super.init(nibName: nil, bundle: nil)
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override var prefersStatusBarHidden: Bool { return true }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        addBackgroundImage()
        addTableView()
        addPopMenu()
        addPagePopButton()
        viewModel.requestData(self.tableView,isRefresh: true, callBackFuc:{})
        viewModel.dataSourceDriver.drive(onNext: { [weak self] _ in
            guard let `self` = self else { return }
            self.tableView.reloadData()
            self.setUpCurrentCellObserver()
           print("监听到数据发生改变")
        }).disposed(by: bag)
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        self.navigationController?.setNavigationBarHidden(true, animated: animated)
    }
    
    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
//        DYPlayerManager.shared.pause(owner: self)
    }
    

    deinit {
        DYPlayerManager.shared.removeAll()
        progressHUD = nil
        cancelledData = nil
        downloadRequest = nil
        destination = nil
        currentTrillEntity = nil
    }
    
    func setUpCurrentCellObserver() {
        print(" cell.isReadyToPlay---<0 ")
        guard let _ = currentObserver else {
            DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) {
                print(" cell.isReadyToPlay---<1 ")
                self.currentObserver = self.currentSubject.asDriver().drive(
                    onNext: { [weak self](index) in
                        guard let `self` = self ,let cell = self.tableView.cellForRow(at: IndexPath(row: index, section: 0)) as? VideoFeedCell else { return }
                      print(" cell.isReadyToPlay---<2 ")
                        if cell.isReadyToPlay {
                            cell.play()
                            print("cell.isReadyToPlay--->3")
                        } else {
                               print("cell.isReadyToPlay--->4")
                            DYPlayerManager.shared.pasueAll()
                            cell.startPlayOnReady = { [weak cell, weak self] in
                                guard let `self` = self, let cell = cell, let indexPath = self.tableView.indexPath(for: cell) else { return }
                                if self.currentSubject.value == indexPath.row {
                                    cell.play()
                                    print("cell.isReadyToPlay--5-->\(self.currentSubject.value)-\(indexPath.row)")
                                }
                            }
                        }
                })
                self.currentObserver?.disposed(by: self.bag)
            }
            return
        }
        print(" cell.isReadyToPlay---<6 ")
    }
}
//MARK:UI 创建
extension VideoFeedViewController {
    func addBackgroundImage() {
        let backgroundImage = UIImageView()
        backgroundImage.image = UIImage(named: "img_video_loading_max375x685")
        view.addSubview(backgroundImage)
        backgroundImage.translatesAutoresizingMaskIntoConstraints = false
        backgroundImage.leftAnchor.constraint(equalTo: view.leftAnchor).isActive = true
        backgroundImage.rightAnchor.constraint(equalTo: view.rightAnchor).isActive = true
        backgroundImage.topAnchor.constraint(equalTo: view.topAnchor).isActive = true
        backgroundImage.bottomAnchor.constraint(equalTo: view.bottomAnchor).isActive = true
    }
    
    func addTableView() {
        tableView.backgroundColor = UIColor(red: 29.0/255.0, green: 22.0/255.0, blue: 33.0/255.0, alpha: 1)
        tableView.register(VideoFeedCell.self, forCellReuseIdentifier: "VideoFeedCell")
        tableView.delegate = self
        tableView.dataSource = self
        tableView.separatorStyle = .none
        tableView.isPagingEnabled = true
        tableView.estimatedRowHeight = self.view.frame.height
        tableView.showsVerticalScrollIndicator = false
        
        tableView.frame = CGRect(x: 0, y: 0, width: screenWidth, height: screenHeight)
        view.addSubview(tableView)
        
//        tableView.translatesAutoresizingMaskIntoConstraints = false
//        tableView.leftAnchor.constraint(equalTo: view.leftAnchor).isActive = true
//        tableView.rightAnchor.constraint(equalTo: view.rightAnchor).isActive = true
//        tableView.topAnchor.constraint(equalTo: view.topAnchor).isActive = true
//        tableView.bottomAnchor.constraint(equalTo: view.bottomAnchor).isActive = true
        //关闭预算高度
//        tableView.estimatedRowHeight = 0;
//        tableView.estimatedSectionHeaderHeight = 0;
//        tableView.estimatedSectionFooterHeight = 0;
        
        if #available(iOS 11.0, *) {
            tableView.contentInsetAdjustmentBehavior = .never
        } else {
            automaticallyAdjustsScrollViewInsets = false
        }
        
//        let header = MJRefreshHeader()
//        header.setRefreshingTarget(self, refreshingAction: #selector(refreshData))
//        tableView.mj_header = header
        
//        let footer = MJRefreshFooter()
//        footer.setRefreshingTarget(self, refreshingAction: #selector(loadData))
//        tableView.mj_footer = footer
        tableView.uHead = URefreshHeader{ [weak self] in self?.refreshData()}
        tableView.uFoot = URefreshFooter { [weak self] in self?.loadData() }
    }
    
    //上拉加载更多
    @objc private func loadData(){
        print("上拉加载更多")
        viewModel.requestData(self.tableView, isRefresh:false, callBackFuc:{} )
    }
    
    @objc private func refreshData(){
        DYPlayerManager.shared.pasueAll()
        viewModel.requestData(self.tableView,isRefresh: true, callBackFuc:{
            if (self.viewModel.videoDataSource.value.count )>0 {
                UIView.animate(withDuration: 0.15, delay: 0.0, options: .curveEaseOut, animations: {
                    self.tableView.scrollToRow(at: IndexPath.init(row: 0, section: 0), at: UITableView.ScrollPosition.top, animated: false)
                   }, completion: { finished in
                    self.currentSubject.accept(0)
                })
                print("----->回顶部")
            }
        })
    }
        
    //下拉菜单
    func addPopMenu(){
        popMenuButton = UILabel()
    
        popMenuButton.frame = CGRect(x: 17, y: (46+heightOfAddtionalHeade)/667*screenHeight, width: 0, height: (30/375)*screenWidth)
        popMenuButton.text = "热门"
        popMenuButton.numberOfLines = 1
        popMenuButton.font = UIFont(name: "PingFang-SC-Bold", size: 16)
        popMenuButton.textColor = .white
        popMenuButton.isUserInteractionEnabled = true
        popMenuButton.textAlignment = .center
        view.addSubview(popMenuButton)
        popMenuButton.sizeToFit() //自适应宽度
        let tap = UITapGestureRecognizer{[weak self](gesture) in
            guard let `self` = self else { return }
            self.showMenu()
        }
        popMenuButton.addGestureRecognizer(tap)
        
        popMenuButtonIcon = UIImageView(image: UIImage(named:"popmenu_icon"))
        view.addSubview(popMenuButtonIcon)
        popMenuButtonIcon.translatesAutoresizingMaskIntoConstraints = false
        popMenuButtonIcon.leftAnchor.constraint(equalTo: popMenuButton.rightAnchor, constant: 5).isActive = true
        popMenuButtonIcon.centerYAnchor.constraint(equalTo: popMenuButton.centerYAnchor).isActive = true
        popMenuButtonIcon.widthAnchor.constraint(equalToConstant: 11).isActive = true
        popMenuButtonIcon.heightAnchor.constraint(equalToConstant: 7).isActive = true
        
    }
    
    @objc func showMenu(){
        popMenu = SwiftPopMenu(menuWidth: (85/375)*screenWidth, arrow: CGPoint(x: popMenuButton.center.x, y: popMenuButton.frame.maxY+5.5), datas: catNameArray)
        popMenu.stateDelega = self
       
        popMenu.didSelectMenuBlock = { [weak self](index:Int)->Void in
            print("我点击的视频分类是\(catNameArray[index])")
            self?.popMenuButton.text = catNameArray[index]
            self?.viewModel.catId = catIDArray[index]
            self?.popMenuButton.sizeToFit() //自适应宽度
            self?.refreshData()
            //列表滚动到第0个
//            if (self?.viewModel.videoDataSource.value.count ?? 0)>0 {
//                UIView.animate(withDuration: 0.15, delay: 0.0, options: .curveEaseOut, animations: {
//                       self?.tableView.scrollToRow(at: IndexPath.init(row: 0, section: 0), at: UITableView.ScrollPosition.top, animated: false)
//                   }, completion: { finished in
//                       self?.currentSubject.accept(0)
//                })
//                print("----->回顶部")
//            }
            self?.popMenu = nil
        }
        popMenu.show()
    }
    
    func addPagePopButton(){
        let button = UIButton()
        button.frame = CGRect(x: view.frame.maxX-32, y: popMenuButton.centerY-(7.5/375)*screenWidth, width: (15/375)*screenWidth, height: (15/375)*screenWidth)
        button.setImage(UIImage(named: "icon_pop"), for: .normal)
        button.addTarget(self, action: #selector(pagePop), for: .touchUpInside)
        view.addSubview(button)
    }
    
    @objc func pagePop(){
        self.navigationController?.popViewController(animated: true)
    }
}

//MARK:列表代理
extension VideoFeedViewController: UITableViewDelegate {
    func numberOfSections(in tableView: UITableView) -> Int {
        return 1
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return view.frame.size.height
    }
}

//MARK:列表数据源
extension VideoFeedViewController: UITableViewDataSource {
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return viewModel.dataSource.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "VideoFeedCell", for: indexPath) as! VideoFeedCell
        let cellViewModel = viewModel.dataSource[indexPath.row]
        cell.bind(viewModel: cellViewModel)
        cell.delegate = self  //设置代理
        return cell
    }
}

//MARK:滚动监听
extension VideoFeedViewController: UIScrollViewDelegate {
    
    //减速动画结束时被调用
    func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
        guard let cell = tableView.visibleCells.first, let index = tableView.indexPath(for: cell) else { return }
        guard currentSubject.value != index.row else { return }
        currentSubject.accept(index.row)
        if index.row == self.viewModel.videoDataSource.value.count-2 && tableView.uFoot.state != .noMoreData && self.viewModel.videoDataSource.value.count>10{
            print("------------>自动加载数据")
            self.loadData()
        }
        print("index.row----scrollViewDidEndDecelerating\(index.row)")
    }
    
    func scrollViewDidEndDragging(_ scrollView: UIScrollView, willDecelerate decelerate: Bool) {
       guard let cell = tableView.visibleCells.first, let index = tableView.indexPath(for: cell) else { return }
       guard currentSubject.value != index.row else { return }
       currentSubject.accept(index.row)
       if index.row == self.viewModel.videoDataSource.value.count-2 && tableView.uFoot.state != .noMoreData && self.viewModel.videoDataSource.value.count>10{
           print("------------>自动加载数据")
           self.loadData()
       }
       print("index.row----scrollViewDidEndDragging\(index.row)")
    }
    
    // 滚动完毕就会调用（如果不是人为拖拽scrollView导致滚动完毕，比如设置setContentOffset时改变会调用)
    func scrollViewDidEndScrollingAnimation(_ scrollView: UIScrollView) {
        guard let cell = tableView.visibleCells.first, let index = tableView.indexPath(for: cell) else { return }
        guard currentSubject.value != index.row else { return }
        currentSubject.accept(index.row)
        if index.row == self.viewModel.videoDataSource.value.count-2 && tableView.uFoot.state != .noMoreData && self.viewModel.videoDataSource.value.count>10{
            print("------------>自动加载数据")
            self.loadData()
        }
        print("index.row------scrollViewDidEndScrollingAnimation\(index.row)")
    }
}

extension VideoFeedViewController:VideoFeedCellTouchDelegate{

    //MARK:-----------------------下载弹窗-----------------------
    func downLoadTouch(trillEntity: TrillEntity) {
        rightButtonTouchType = .download
        currentTrillEntity = trillEntity
        let pastboard = UIPasteboard.general
        pastboard.string = currentTrillEntity.itemshorttitle
        downloadEvent()
    }
    
    //MARK:-----------------------文案推广弹窗-----------------------
    func copyTextBtnTouch(trillEntity: TrillEntity) {
        currentTrillEntity = trillEntity
        rightButtonTouchType = .copyText
        let attrString = NSMutableAttributedString(string: currentTrillEntity.guideArticle ?? "")
        let attr: [NSAttributedString.Key : Any] = [.font: UIFont(name: "PingFang-SC-Regular", size: 14)!,.foregroundColor: UIColor(red: 0.4, green: 0.4, blue: 0.4,alpha:1)]
        attrString.addAttributes(attr, range: NSRange(location: 0, length: attrString.length))
        let containerView = CopyTextPopView()
        containerView.copyBtnTouch = {[weak self] in
            guard let `self` = self else { return }
            UIPasteboard.general.string = "\(String(describing: self.currentTrillEntity.itemshorttitle))"
            containerView.jx_popupView?.dismiss(animated: true, completion: nil)
            showToast("复制成功",view:self.view)
        }
        containerView.copyTextLabel.attributedText = attrString
        let containerViewSize:CGSize = CGSize(width: (300/375)*screenWidth, height: (210/375)*screenWidth)
        containerView.frame.size = containerViewSize
        containerView.frame.origin = CGPoint(x: (screenWidth-containerViewSize.width)/2, y: (screenHeight-containerViewSize.height)/2)
        let animator = JXPopupViewLeftwardAnimator()
        let downloadFinshedPopupView = JXPopupView(containerView:UIApplication.shared.keyWindow! , contentView: containerView, animator: animator)
        downloadFinshedPopupView.isDismissible = true
        downloadFinshedPopupView.isInteractive = true
        downloadFinshedPopupView.isPenetrable = false
        downloadFinshedPopupView.backgroundView.style = .solidColor
        downloadFinshedPopupView.backgroundView.blurEffectStyle = UIBlurEffect.Style.light
        downloadFinshedPopupView.backgroundView.color = UIColor.black.withAlphaComponent(0.3)
        downloadFinshedPopupView.display(animated: true, completion: nil)
    }
    
    
    //MARK:-----------------------分享弹窗-----------------------
    func shareBtnTouch(trillEntity: TrillEntity) {
        currentTrillEntity = trillEntity
        let containerView = BottomShareView()
        containerView.cancelBtnTouch = {
             containerView.jx_popupView?.dismiss(animated: true, completion: nil)
        }
        containerView.saveVideoBtnTouch = {[weak self] in
            guard let `self` = self else { return }
            containerView.jx_popupView?.dismiss(animated: true, completion: nil)
            self.rightButtonTouchType = .shareSave
            self.downloadEvent()
        }
        containerView.weatchBtnTouch = {[weak self] in
            guard let `self` = self else { return }
            containerView.jx_popupView?.dismiss(animated: true, completion: nil)
            self.rightButtonTouchType = .shareFriend
            self.downloadEvent()
        }
        containerView.friendCircleBtnTouch = {[weak self] in
            guard let `self` = self else { return }
            containerView.jx_popupView?.dismiss(animated: true, completion: nil)
            self.rightButtonTouchType = .shareFriendCircle
            self.downloadEvent()
        }
        containerView.frame = CGRect(x: 0, y: (488.5/667)*screenHeight ,width: screenWidth, height: (178.5/667)*screenHeight)
        let animator = JXPopupViewUpwardAnimator()
        let downloadFinshedPopupView = JXPopupView(containerView:UIApplication.shared.keyWindow! , contentView: containerView, animator: animator)
        downloadFinshedPopupView.isDismissible = true
        downloadFinshedPopupView.isInteractive = true
        downloadFinshedPopupView.isPenetrable = false
        downloadFinshedPopupView.backgroundView.style = .solidColor
        downloadFinshedPopupView.backgroundView.blurEffectStyle = UIBlurEffect.Style.light
        downloadFinshedPopupView.backgroundView.color = UIColor.black.withAlphaComponent(0.3)
        downloadFinshedPopupView.display(animated: true, completion: nil)
    }
    
    @objc func downLoadCompletePopView() {
          let containerView = DownloadPopView()
            containerView.confirmBtnTouch = {
            containerView.jx_popupView?.dismiss(animated: true, completion: nil)
          }
          containerView.jumpWeChatBtnTouch = {[weak self] in
            guard let `self` = self else { return }
            containerView.jx_popupView?.dismiss(animated: true, completion: nil)
            self.urlLauncher(self.currentTrillEntity.guideArticle ?? "")
          }
          let containerViewSize:CGSize = CGSize(width: (300/375)*screenWidth, height: (180/375)*screenWidth)
          containerView.frame.size = containerViewSize
          containerView.frame.origin = CGPoint(x: (screenWidth-containerViewSize.width)/2, y: (screenHeight-containerViewSize.height)/2)
          let animator = JXPopupViewLeftwardAnimator()
          let downloadFinshedPopupView = JXPopupView(containerView:UIApplication.shared.keyWindow! , contentView: containerView, animator: animator)
          downloadFinshedPopupView.isDismissible = true
          downloadFinshedPopupView.isInteractive = true
          downloadFinshedPopupView.isPenetrable = false
          downloadFinshedPopupView.backgroundView.style = .solidColor
          downloadFinshedPopupView.backgroundView.blurEffectStyle = UIBlurEffect.Style.light
          downloadFinshedPopupView.backgroundView.color = UIColor.black.withAlphaComponent(0.3)
          downloadFinshedPopupView.display(animated: true, completion: nil)
      }
    
    func downloadEvent(){
        self.progressHUD = MBProgressHUD.showAdded(to: self.view, animated: true)
        self.progressHUD.mode = .determinate
        self.progressHUD.progress = 0
        self.progressHUD.label.text = "当前进度：1%"
        Alamofire.download(currentTrillEntity.dyVideoUrl ?? "").downloadProgress(queue: DispatchQueue.main) { (progress) in
            self.progressHUD.progress = Float(progress.fractionCompleted)
            self.progressHUD.label.text = "下载中\(String(format:"%.0f", progress.fractionCompleted*100))%"
        }
        //下载存储路径
        self.destination = {_,response in
            let documentsUrl = FileManager.default.urls(for: .documentDirectory, in: FileManager.SearchPathDomainMask.userDomainMask).first
            let fileUrl = documentsUrl?.appendingPathComponent(response.suggestedFilename!)
            return (fileUrl!,[.removePreviousFile, .createIntermediateDirectories] )
        }
        self.downloadRequest = Alamofire.download(currentTrillEntity.dyVideoUrl ?? "", to: self.destination)
        self.downloadRequest.responseData(completionHandler: downloadResponse)
    }
    
    //根据下载状态处理
    func downloadResponse(response:DownloadResponse<Data>){
        switch response.result {
        case .success:
            self.saveVideoUrl(string: (response.destinationURL?.path)!)
        case .failure:
            self.cancelledData = response.resumeData//意外停止的话,把已下载的数据存储起来
        }
    }
     
    //将下载的网络视频保存到相册
    func saveVideoUrl(string:String) {
        if string != ""{
            if UIVideoAtPathIsCompatibleWithSavedPhotosAlbum(string){
                UISaveVideoAtPathToSavedPhotosAlbum(string, self, #selector(self.saveVideoCallBack(videoPath:didFinishSavingWithError:contextInfo:)), nil)
            }
        }
    }
    
    //将下载的网络视频保存到相册
    @objc func saveVideoCallBack(videoPath: String, didFinishSavingWithError error: NSError, contextInfo info: AnyObject) {
        self.progressHUD.hide(animated: true)
        if error.code != 0{
            showToast("保存失败",view:view)
            let  alertController = UIAlertController(title: "提示", message: "请前往设置中打开相册访问权限", preferredStyle :.alert)
            let settingsAction = UIAlertAction(title: "前往", style:.default) { (action) in
                guard let url = URL(string: UIApplication.openSettingsURLString), UIApplication.shared.canOpenURL(url) else {
                    return
                }
                  UIApplication.shared.openURL(url)
            }
            alertController.addAction(settingsAction)
            let cancelAction = UIAlertAction(title: "取消", style: .cancel, handler: nil)
            alertController.addAction(cancelAction)
            present(alertController, animated: true, completion: nil)
            print(error)
        }else{
            switch self.rightButtonTouchType {
            case .download:
                self.downLoadCompletePopView()
                print("下载视频")
                break
            case .shareSave:
                showToast("保存成功",view:view)
                break
            case .shareFriend:
                showToast("保存成功",view:view)
                sharedVideo(videoPath)
                break
            case .shareFriendCircle:
               showToast("保存成功",view:view)
               sharedVideo(videoPath)
               break
            default:
                return
            }
        }
    }
    
    //调用系统分享
    func sharedVideo(_ fileURLWithPath:String){
        let videoUrl = URL(fileURLWithPath: fileURLWithPath)
        let toVC = UIActivityViewController(activityItems: [videoUrl], applicationActivities: nil)
        toVC.excludedActivityTypes =  [
            UIActivity.ActivityType.postToWeibo,
            UIActivity.ActivityType.print,
            UIActivity.ActivityType.copyToPasteboard,
            UIActivity.ActivityType.assignToContact,
            UIActivity.ActivityType.saveToCameraRoll,
            UIActivity.ActivityType.addToReadingList,
            UIActivity.ActivityType.postToFlickr,
            UIActivity.ActivityType.postToVimeo,
            UIActivity.ActivityType.postToTencentWeibo
        ]
        present(toVC, animated: true, completion: {[weak self] in
            guard let `self` = self else { return }
            showToast("分享成功",view:self.view)
        })
    }
    
    //打开微信
    func urlLauncher(_ text:String){
        let urlStr = "weixin://"
        let encodeUrlString = urlStr.addingPercentEncoding(withAllowedCharacters:
              .urlQueryAllowed)
        if let url = URL(string: encodeUrlString!) {
            //根据iOS系统版本，分别处理
            if #available(iOS 10, *) {
                  UIApplication.shared.open(url, options: [:],
                                            completionHandler: {
                                              (success) in
                  })
              } else {
                  UIApplication.shared.openURL(url)
              }
          }
    }
}

extension VideoFeedViewController:SwiftPopMenuStateDelegate{
    func swiftPopMenuState(iShow: Bool) {
        if iShow {
            popMenuButtonIcon.image = UIImage(named: "popmenu_icon_S")
        }
        else{
             popMenuButtonIcon.image = UIImage(named: "popmenu_icon")
        }
    }
}
